
/* CMS generic js
 *
 * Dependency: tvb-utils.js
 *             tvb-coockie.js
 *             jquery-1.4.2.js
 *             jquery-laughing.js
 *             jquery.jqgrid-3.6.2.js
**/

TVB.util.namespace('TVB.Cms.Components');

TVB.Cms.Components = {

    header: function (scope) {
        var alignWidth = function () {
            $(".cms-header>ul>li", scope).each(function () {
                var w1, w2;
                w1 = $(this).width();
                w2 = $(this).children('ul').width();
                if (w2 < w1) {
                    $(this).children('ul').width(w1 - 2);    //align the width of submenu with header
                }
            });
        };
        $(".cms-header li", scope).hover(function () {
            TVB.util.once(alignWidth);    //init on the fly.
            $(this).addClass('ui-state-hover');
        }, function () {
            $(this).removeClass('ui-state-hover');
        });
    },

    superfish: function () {

    	$.extend($.fn.superfish.defaults, {
    		hoverClass	: 'sfHover',
    		pathClass	: 'overideThisToUse',
    		pathLevels	: 1,
    		delay		: 0,
    		animation	: {opacity:'show'},
    		speed		: 'fast',
    		disableHI	: true		// true disables hoverIntent detection
    	});


        $("ul.sf-menu").supersubs({ 
            minWidth:    10,   // minimum width of sub-menus in em units 
            maxWidth:    15,   // maximum width of sub-menus in em units 
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                               // due to slight rounding differences and font-family 
        }).superfish();  // call supersubs first, then superfish, so that subs are 
                         // not display:none when measuring. Call before initialising 
                         // containing tabs for same reason. 
    },

    laughing: function (scope) {
        $(scope).find(".input_status").input_status();
        $(scope).find(".ruler").ruler();
    },

    textarea: function (scope) {
        $(scope).find(".cms-textarea textarea").one('focus', function () {
            $(this).text_status().focus();
        }).each(function () {    //auto expand all textarea
            var that = this;
            setTimeout(function () {
                $(that).height(80);
                var h1 = that.offsetHeight,
                    h2 = that.scrollHeight;
                if (h1 < h2) {
                    $(that).height(h2);
                }
            }, 200);
        });
    },

    datepicker: function (scope) {

    	$.datepicker._doKeyUp = function(event) {
    		var inst = $.datepicker._getInst(event.target);
    		if (inst.input.val() != inst.lastVal) {
    			try {
    				var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
    					(inst.input ? inst.input.val() : null),
    					$.datepicker._getFormatConfig(inst));
    				if (date) { // only if valid
    					$.datepicker._setDateFromField(inst);
    					$.datepicker._updateAlternate(inst);
    					//$.datepicker._updateDatepicker(inst);    //commented by simon to handle the conflict with the "mask" plugin
    				}
    			}
    			catch (event) {
    				$.datepicker.log(event);
    			}
    		}
    		return true;
    	};

        var timer;
        //reset the position of DatePicker 
        $.datepicker._checkOffset = function(inst,offset,isFixed){return offset;};

        $(scope).find("input.cms-datepicker").datepicker({
            dateFormat: 'yy-mm-dd'
        }).one("focus", function () {
            $(this).unmask().mask("9999-19-39");
        }).blur(function (e) {
            var pattern = /^[\d]{4}\-\d{2}\-\d{2}$/,
                value = this.value,
                that = this;
            if (value !== '' && value !== '____-__-__' && !pattern.test(value)) {
                //alert(TVB.Pdes.Config.TXT.INVALID_DATE_FORMAT);
                clearTimeout(timer);
                timer = setTimeout(function () {
                    that.focus();
                }, 500);
            }
        });

        $('#ui-datepicker-div').click(function () {
            clearTimeout(timer);
        });
    },

    time: function (scope) {
        $(scope).find(".cms-time").time_widget([
            [ ['60', '+1 hour'], ['15', '+15 minutes'] ],
            [ ['-15', '-15 minutes'], ['-60', '-1 hour'] ]
        ]).keydown(
            function (event) {
                if(13 == event.keyCode){                
                    return false;
                } 
            }
        ).one("focus", function () {
            $(this).unmask().mask("29:59");
        });
        $('.cms-time-hhmmss input', scope).one('focus', function () {
            $(this).unmask().mask("29:59:59");            
        });

    },

    button: function (scope) {
        $('.cms-btn.btn-back', scope).click(function () {
            history.back();
        });
        $('.cms-btn.btn-back2list', scope).click(function () {
            window.location = TVB.util.getUrlInSession();
        });
        $('.cms-btn.btn-link', scope).click(function () {
            window.location = $(this).attr('href');
        });
        $("input[type=button], input[type=submit], .cms-btn", scope).hover(function () {
            $(this).addClass('ui-state-hover');
        }, function () {
            $(this).removeClass('ui-state-hover');
        });
    },
    
    autocomplete: function (scope) {
        /*var options = {
            returnHandler : function (data, input) {
                var id = data.id,
                    type = data.type,
                    value = data[type],
                    $input = $(input);
                $input.parent().find('input.ac_val').val(id);
                $input.parent().find('input.cms-autocomplete').val(value);
            },
    	    parse : function (data) {
        		var parsed = [], type;
                var rows = eval('(' + data + ')');
        		for (var i=0; i < rows.length; i++) {
                    var row = rows[i];
        			if (row) {
                        type = row.type;
        				parsed[parsed.length] = {
        					data: row,
        					value: row[type],
        					result: row[type]
        				};
        			}
        		}
        		return parsed;
        	},
    	    formatItem : function (row) {
                var type = row.type;
                return TVB.util.toHtmlEntities(row[type]);
            }
        };*/


        $('input.cms-autocomplete', scope).each(function (i){
            var url = $(this).next("input[type='hidden'].ac_url").val();
            //$(this).autocomplete(url, options);
            var _this = $(this);
            
            var $hidden = _this.siblings("input.ac_config");
            var json = $.parseJSON($hidden.val());
            $hidden.remove();
            
            var options = {
                minLength : 1,
                select : function (event, ui){
                    var v = (typeof ui.item.id === 'undefined') ? ui.item.value : ui.item.id;
                    _this.parent().find('input.ac_val').val(v);
                    return false;
                }
            };
            $.extend(options, json);
            
            $ac = _this.autocomplete(options);

        });

    },

    label: function (scope) {
        $('.cms-form-item .grid-l label', scope).click(function () {
            $(this).closest('.cms-form-item').find(
                '.grid-r > input:first-child, .grid-r > textarea'
            ).focus();
            $(this).closest('.cms-form-item').find(
                '.grid-r > input[type="checkbox"]:only-child'
            ).click();
        });
    },
	
	editableList: function (scope) {
		var instance = function(jJson,jTable,jAddBtn,jAddText){
			this.id = 0;
			this.jJson = jJson;
			this.oJson = [];
			this.jTable = jTable;
			this.jAddBtn = jAddBtn;
			this.jAddText = jAddText;
			this.sTemplate = jTable.attr("template");
			var othis = this;
			var completeData = JSON.parse(this.jJson[0].value);
			for(var i=0;i<completeData.length;i++){
				for(var key in completeData[i]){
					othis.addItem(completeData[i][key],key);
					break;
				}
			}
			jAddBtn.click(function(e){
				othis.addItem(othis.jAddText[0].value,null);
				return false;
			});
			this.jTable.click(function(e){
				var target = e.target;
				switch(target.className.split(" ")[0]){
					case "move-up":
						var jTr = $(target.parentNode.parentNode);
						othis.moveUp(jTr);
					break;
					case "move-down":
						var jTr = $(target.parentNode.parentNode);
						othis.moveDown(jTr);
					break;
					case 'move-del':
						var jTr = $(target.parentNode.parentNode);
						othis.delItem(jTr);
					break;
				}
				return false;
			});
		};
		instance.prototype = {
			moveUp:function(jItem){
				var o = jItem.prev("tr");
				var json = jItem.data("json");
				var index = jQuery.inArray(json,this.oJson);
				if(index>0){
					this.oJson.splice(index,1);
					this.oJson.splice(index-1,0,json);
					this.jJson[0].value = JSON.stringify(this.oJson);
				}
				o.before(jItem); 
			},
			moveDown:function(jItem){
				var o = jItem.next("tr");
				var json = jItem.data("json");
				var index = jQuery.inArray(json,this.oJson);
				this.oJson.splice(index,1);
				this.oJson.splice(index+1,0,json);
				this.jJson[0].value = JSON.stringify(this.oJson);
				o.after(jItem);
			},
			delItem:function(jItem){
				var json = jItem.data("json");
				var index = jQuery.inArray(json,this.oJson);
				this.oJson.splice(index,1);
				this.jJson[0].value = JSON.stringify(this.oJson);
				jItem.remove();
			},
			addItem:function(value,data){
				if(data === null){data = this.id;this.id ++;}
				var str = this.sTemplate.replace("{value}",value);
				var tr = $(str).appendTo($("tbody",this.jTable));
				var item = {};
				item[data] = value;
				this.oJson.push(item);
				this.jJson[0].value = JSON.stringify(this.oJson);
				tr.data("json",item);			
			},
			editItem:function(){
				
			},
			viewItem:function(){
				
			}
		};
		var dModule = $(".cms-editable-list.edit-model");
		var jJson = $("input.json-str",dModule);
		var jTable = $("table.result",dModule);
		var jAddBtn = $("input.add-item",dModule);
		var jAddText = $("input.text-item",dModule);
		for(var i=0;i<dModule.length;i++){
			new instance($(jJson[i]),$(jTable[i]),$(jAddBtn[i]),$(jAddText[i]));
		}
	},
	jqgrid : function (scope) {

        $(".cms-jqgrid", scope).each(function (i){

            var tbl = $("table.scroll",this).attr("id", TVB.util.genId()),
                pager = $("div.scroll",this).attr("id", TVB.util.genId()),
                $hidden = $("input[type=hidden]", this),
                json = $.parseJSON($hidden.val());
            //$hidden.remove();
                options = {
                    datatype : "json",
                    rowNum : "10",
                    rowList : [10,20,30,40,50],
                    imgpath : "",
                    pager : pager,
                    viewrecords : true,
                    height : "auto",
                    sortname : json.colModel[0].name,
                    sortorder : "desc"
                };
            $.extend(options, json);
            
            if(json.tabs){
        
                var tt,i,j,k,default_checked=0,
                    tabs = json.tabs,
                    colNames = json.colNames,
                    colModel = json.colModel,
                    tmp = '<div class="cms-jqgrid-tabs ui-tabs ui-helper-clearfix">';
                    tmp += '<ul class="ui-tabs-nav ui-helper-clearfix">';
                json.tabs = null;
                for(i=0,l=tabs.length;i<l;i++){
                    if(tabs[i].checked){
                        default_checked = i;
                    }
                }
                for(i=0,l=tabs.length;i<l;i++){
                    if(!tabs[i].title){
                        tt=[];
                        j=0;
                        for(j in tabs[i].cols){
                            k=0;
                            for(k in colModel){
                                if(tabs[i].cols[j]==colModel[k].name){
                                    tt[tt.length] = colNames[k];
                                }
                            }
                        }
                        tabs[i].title = tt.join(', ');
                    }
                    
                    if(i===default_checked){               
                        tmp += '<li class="ui-state-default ui-corner-top ui-state-active"><a href="#'+i+'">'+tabs[i].title+'</a></li>';
                        
                    }else{       
                        for(j in tabs[i].cols){
                            k=0;
                            for(k in colModel){
                                if(tabs[i].cols[j]==colModel[k].name){
                                    colModel[k].hidden = true;
                                }
                            }
                        }                  
                        tmp += '<li class="ui-state-default ui-corner-top"><a href="#'+i+'">'+tabs[i].title+'</a></li>';
                    }                
                }
                tmp += '<li class="ui-state-default ui-corner-top"><a href="#'+i+'">View All</a></li>';
                tmp += '</ul></div>';
                tbl.before(tmp);
                tbl.prev(".cms-jqgrid-tabs").find("a").click(function (){
                    var nav = $(this).parents(".ui-tabs-nav"),
                        len = $("li",nav).length,
                        cur = $("li",nav).index($("li.ui-state-active",nav)),               
                        idx = $("a",nav).index(this);
                    if(idx+1 == len){
                        for(i in colModel){
                            tbl.jqGrid('showCol',colModel[i].name);
                        }
                    }else if(cur != idx){
                        for(i in tabs){
                            for(j in tabs[i].cols)
                            tbl.jqGrid('hideCol',tabs[i].cols[j]);
                        }
                        for(i in tabs[idx].cols){
                            tbl.jqGrid('showCol',tabs[idx].cols[i]);
                        }                    
                    }
                    $("li.ui-state-active",nav).removeClass("ui-state-active");
                    $(this).parent().addClass("ui-state-active");
                    return false;
                });
                var reset_width = function (){
                    var cms_jg = $(this).parents(".cms-jqgrid"),
                        w = cms_jg.width()-2;                                        
                    $(".ui-jqgrid", cms_jg).width(w);
                    $(".ui-jqgrid-view", cms_jg).width(w);
                    $(".ui-jqgrid-hdiv", cms_jg).width(w);
                    $(".ui-jqgrid-bdiv", cms_jg).width(w);                    
                    $(".ui-jqgrid-pager", cms_jg).width(w);
                };
                if(!!options.loadComplete){
                    var tmp = options.loadComplete;
                    options.loadComplete = function (){
                        reset_width.apply(this);
                        tmp.apply(this);
                    };
                }else{
                    options.loadComplete = reset_width;
                }
            }
            
            var filter_form = $(this).parents(".cms-mod").find('form');
            var filters, url;
            if ($(this).closest('.cms-mod form').length > 0) {    //jqgrid in form
                filters = encodeURIComponent(filter_form.serialize());
                url = json.url;
                json.url = (url.indexOf('?') == -1) ? url+'?filters='+filters : url+'&filters='+filters; 
            } else if (filter_form.length > 0){
                filter_form.submit(function (){ 
                    var filters = encodeURIComponent($(this).serialize());
                    var url = json.url;
                    url = (url.indexOf('?') == -1) ? url+'?filters='+filters : url+'&filters='+filters ; 
                    tbl.jqGrid().setGridParam({url:url}).trigger('reloadGrid');
                    return false;
                });
            }
            
            tbl.jqGrid(options).navGrid(pager,{edit:false,add:false,del:false,search:false});
            $(this).data('jqgrid', tbl.jqGrid());

            //for back2list
            TVB.util.once(TVB.util.saveUrlInSession);

        });
    },
    dialog: function (scope) {
        var defaults = {
            bgiframe: true,
            resizable: false,
            width: 970,
            autoOpen: false,
            modal: true,
            title: 'Dialog'
        };
        $('.cms-dialog', scope).each(function () {
            var $hidden = $('div.bd + input.config', this);
            var json = $.parseJSON($hidden.val());
            $hidden.remove();
            var config = $.extend({}, defaults, json);
            $(this).dialog(config);
        });
    },
    dragtosort: function (scope) {
        var defaults = {
            placeholder: 'ui-state-highlight',
            cursor: 'move',
            update: function (event, ui) {
                var dts = ui.item.parents(".cms-dragtosort");
                var hidden = $(".orders", dts);
                var sort = [];
                $("li",dts).each(function () {
                    sort[sort.length] = $("input[type=hidden]",this).val();
                });
                hidden.val(sort.join('_'));
            }
        };
        $('.cms-dragtosort').bind('renderJson', function (event,json){
            if(json){
                var tmp1 = [];
                var tmp2 = [];
                for(i in json){ 
                    tmp1[tmp1.length] = '<li class="ui-widget-content"><span class="ui-icon ui-icon-arrow-4"></span><em>'+json[i].name+'</em><input type="hidden" value="'+json[i].id+'" /></li>';
                    tmp2[tmp2.length] = json[i].id;
                }
                $("ul", this).html(tmp1.join(""));
                $("input.orders", this).val(tmp2.join("_"));
            }
        });
        $('.cms-dragtosort ul', scope).each(function (){
            var config = $.parseJSON($(this).siblings("input.config", this).val());
            var options = $.extend(defaults, config);
            
            $(this).sortable(options);
            $(this).disableSelection();

        });
    },
    logout: function () {
        $('a.cms-logout').click(function (e) {
            var authCookie = $(this).next('.auth-cookie').val(),
                o, name, domain, options = {path: '/'};
            if (authCookie !== '') {
                o = eval('(' + authCookie + ')'),
                name = o.name,
                domain = o.domain;
                if (domain !== '') {
                    //document.domain = domain;
                    options.domain = domain;
                }
                e.preventDefault();
                if (TVB.util.isSet('TVB.cookie.remove')) {
                    TVB.cookie.remove(name, options);
                    window.location.reload();
                }
            }
        });
    },

    validation: function () {
        if ($.validator) {

            $.validator.addMethod('regexp', function (value, element, params) {
                var regex = new RegExp(params.substring(1, params.length-1));
                var result = this.optional(element) || regex.test(value);
                return result;	
            }, "Invalid format");
            $.validator.addMethod('path', function (value, element) {
                return this.optional(element) || /^[a-zA-Z]\w*$/.test(value);
            }, "Alphanumeric. Shoulde begin with character.");
            $.validator.addMethod('english', function (value, element) {
                return this.optional(element) || /^[\x00-\xff]*$/.test(value);
            }, "Alphanumeric and punctuation only.");
            $.validator.addMethod('positiveInt', function (value, element) {
                return this.optional(element) || /^[1-9]\d*$/.test(value);
            }, "Positive integer only.");

            //ignor hidden fileds
            $.validator.defaults.ignore = ':hidden';

            if (TVB.util.isSet('CMS.oValidation')) {
                $(CMS.oValidation.form).validate({
                    rules: CMS.oValidation.rules,
                    errorClass: "error"
                });
            }

        }
    }

};
/*
**  country list
*/
TVB.Cms.Components.countryList = function(scope){
	var scope = $('div.cms-countrylist-item', scope), scopeDialog;
	if(!scope.length){
		return false;
	}
	var countryData = {
		handle: null,
		init: function(scope){
			this.handle = $('input.vcountry', scope);
		},
		set: function(data){
			this.handle.val( JSON.stringify(data) );
            this.handle.trigger('change');
		},
		get: function(){
			return eval('('+ this.handle.val() +')');
		}
	};
	
	var refreshCountryList = function(scope){
		countryData.init(scope);
		var i,j,k,item, dla,listEl = $('.grid-r .list', scope), data = countryData.get();
		listEl.html('');
		for(i in data){
			if(data[i] == 'ALL'){
				dla = $('<p class="a"><b>'+i+'</b> - <span class="b"><em>ALL</em></span></p>');
				listEl.append(dla);
			}else{
				for(j in data[i]){
					dla = $('<p class="a"><b>'+i+'</b> - <span class="b"></span></p>');
					var item = data[i][j], dlb;
					if(item == 'ALL'){
						//dlb = $('<dl class="c"><dt>'+j+'</dt><dd class="d"><p>ALL</p></dd></dl>');
					}else{
						var ps = [];
						for(k in item){
							ps.push('<em>'+item[k]+' ('+k+')</em>');
						}
						dlb = $(ps.join('<ins>,</ins>'));
					}
					$('.b', dla).append(dlb);
					listEl.append(dla);
				}
			}
		}
		$('dl', listEl).addClass('ui-helper-clearfix');
		$('dd', listEl).addClass('ui-helper-clearfix');
		$('em', listEl).append('<span class="ui-icon ui-icon-close"></span>');
	};
	for(var i=0,ilen=scope.length; i<ilen; i++){
		refreshCountryList(scope[i]);
	}
	var matchCountryOnSub = function(index){
		var uitab = getUiTab( scopeDialog );
		var mslis = $('.subtabs ul li', scopeDialog), msli=mslis.eq(index);
		if(msli.length != 1){
			msli = mslis.eq(0);
			index = 0;
		}
		var txt = msli.text().toLowerCase(),
			re = new RegExp('(['+txt+']{1})', 'i');
		mslis.removeClass('ui-tabs-selected ui-state-active');
		msli.addClass(' ui-tabs-selected ui-state-active');
		$('div', uitab).css('display', 'none');
		$('div.'+txt, uitab).css('display', '');
	};
	
	var initCountrySubTabs = function(){
		var i=0;
		$('.subtabs li', scopeDialog).hover(function(e){
			$(this).addClass('ui-state-hover');
		}, function(e){
			$(this).removeClass('ui-state-hover');
		}).each(function(){
			$(this).attr('index', i);
			i++;
		});
		
		$('.subtabs li', scopeDialog).bind('click', function(e){
			e.preventDefault();
			var t=e.target.nodeName == 'A' ? $(e.target).parents('li').eq(0) : $(e.target), 
				i=0, index=0,
				uitab = getUiTab( scopeDialog );
			$('.subtabs ul li', scopeDialog).each(function(){
				if(t[0] == this){
					index = i;
				}
				i++;
			});
			matchCountryOnSub(index);
			uitab.attr('sindex', index);
		});
	};
	
	var initCountryTabs = function(){
		
		scopeDialog.tabs({
			cache: true,
			selected: $('.tabs',scopeDialog).attr('selectIndex'),
			ajaxOptions: {
				success: function(r, s){
					countryData.init(scope);
					if(s == 'success'){
						var sdatas={}, data = eval('('+r+')'), oData = countryData.get(), 
							uitabs = getUiTab( scopeDialog ), sublist = $(".subtabs li", scopeDialog),
							mregin='';
						uitabs.addClass('list');
						uitabs.html('');
						for(var i in data){
							mregin= i;
							for(var j in data[i]){
								var mname = data[i][j][0]+' ('+j+')';
								for(var si=0, slen=sublist.length; si<slen; si++){
									var txt = sublist.eq(si).text().toLowerCase(),
										re = new RegExp('(['+txt+']{1})', 'i'),
										matches = data[i][j][0].substr(0,1).match(re);
									if(!sdatas[txt]){
										sdatas[txt] = []
									}
									if(matches && matches[1]){
										sdatas[txt].push([j, data[i][j][0], data[i][j][1]]);
										//break;
									}
								}
							}
						}
						for(var i in sdatas){
							var div=$('<div class="sub '+i+'"></div>'),
								dl = $('<dl><dt>'+mregin+'</dt><dd></dd></dl>'), dd=$('dd', dl);
							div.append(dl);
							div.append('<dl class="end"><dt>&nbsp;</dt><dd><p><label><input type="checkbox" class="all" />&nbsp;ALL</label></p></dd></dl>');
							
							for(var j in sdatas[i]){
								var mname = sdatas[i][j][1]+' ('+sdatas[i][j][0]+')',
									mchecked = false;
								if( oData[mregin] ){
									if(oData[mregin][mregin] && oData[mregin][mregin][sdatas[i][j][0]]){
										mchecked = true;
									}
									if(oData[mregin] == 'ALL'){
										mchecked = true;
										$('dl input.all', div).attr('checked', 'checked');
										$('input[disabled]', div).removeAttr('checked');
									}
								}
								mname = sdatas[i][j][2] ? '<s>'+mname+'</s>' : mname;
								var p = $('<p><label><input type="checkbox" value="'+sdatas[i][j][0]+'" name="'+sdatas[i][j][0]+'" label="'+sdatas[i][j][1]+'" '+(sdatas[i][j][2] ? 'disabled' : '')+' '+(mchecked ? 'checked': '')+' /> '+mname+'</label></p>');
								dd.append(p);
							}
							uitabs.append(div);
						}
						uitabs.attr('sindex', 0);
						matchCountryOnSub(0);
					}
				},
				error: function(xhr, status, index, anchor) {
					$(anchor.hash).html("Couldn't load this tab. We'll try to fix this as soon as possible. If this wouldn't be a demo.");
				}
			},
			show: function(a,b){
				var uitab=getUiTab( scopeDialog ), sindex= uitab.attr('sindex');
				matchCountryOnSub( sindex );
			}
		});
		$(".ui-tabs-nav", scopeDialog).switchClass('ui-corner-all', 'ui-corner-top');
		//$(".cms-countrylist-pop .subtabs").css('width', $(".cms-countrylist-pop").width() - 80);
		scopeDialog.bind('click', function(e){
			var t = $(e.target);
			if(t.hasClass('all')){
				var sindex=$(".subtabs li.ui-tabs-selected", scopeDialog).attr('index'), 
					uitabs = getUiTab( scopeDialog ),
					subdiv = t.parents('div.sub').eq(0);
				
				if(t[0].checked){
					$('input', subdiv).attr('checked', 'checcked');
					$('input[disabled]', subdiv).removeAttr('checked');
				}else{
					$('input', subdiv).removeAttr('checked');
				}
			}else if(e.target.nodeName == 'INPUT' && $(e.target).attr('type') == 'checkbox'){
				if(e.target.checked == false){
					t.parents('div.sub').find('input.all').removeAttr('checked');
				}
			}else if(t.hasClass('first-btn')){
				submitTabsForm(e);
			}
		});
	};
	var setCountryDataByDel = function(scope){
		if(!scope){return true}
		countryData.init(scope);
		scopeDialog = $('#'+ scope.attr('dialog'));
	
		var datas = {}, oData = countryData.get(), tabs=$('.list .a', scope);
		for(var i=0, ilen=tabs.length; i<ilen; i++){
			var k = $('b', tabs.eq(i)).text(), mlis = $('em', tabs.eq(i));
			datas[k] = datas[k] || {};
			if(mlis.eq(0).text() == 'ALL'){
				datas[k] = 'ALL';
			}else{
				datas[k][k] = datas[k][k] || {};
				for(var j=0,jlen=mlis.length; j<jlen; j++){
					var matches = mlis.eq(j).text().match(/([^\(]+)\(([^\)]+)\)/i);
					if(matches && matches[1]){
						datas[k][k][matches[2]] = matches[1];
					}
				}
			}
		}
		countryData.set(datas);
	};
	var setCountryData = function(scope){
		if(!scope){return true}
		countryData.init(scope);
		scopeDialog = $('#'+ scope.attr('dialog'));
		
		var datas = {}, oData = countryData.get(), tabs=$('.tabs li', scopeDialog);
		for(var i=0, ilen=tabs.length; i<ilen; i++){
			var item=null,isv=false, item2={}, item2len=0,tab = tabs.eq(i), uitab = $('.ui-tabs-panel', scopeDialog).eq(i), dls = $('dl', uitab),selectall=1;
			if(!uitab.hasClass('list')){
				if(oData[tab.text()]){
					datas[tab.text()] = oData[tab.text()];
				}
				continue;
			}
			$('input.all', uitab).each(function(){
				if( !this.checked){ selectall=0;}
			});
			if(selectall && $('input.all', uitab).length){
				item = 'ALL';
				isv=true;
			}else{
				item = {};
				for(var j=0,jlen=dls.length; j<jlen; j++){
					if(!$(dls[j]).hasClass('end')){
						var key2 = $('dt', dls[j]).text(), vals = $('dd input', dls[j]);
						for(var ii=0, iilen=vals.length; ii<iilen; ii++){
							if(vals[ii].checked){
								item2len++;
								var mkk2 = vals[ii].value
								item2[mkk2] = $(vals[ii]).attr('label');
							}
						}
						if(item2len){
							item[key2] = item2;
							isv=true;
						}
					}
				}
			}
			if(isv){
				datas[tab.text()] = item;
				isv=false;
			}
		}
		
		countryData.set(datas);
	};
	var submitTabsForm = function(e){
		e.preventDefault(); 
		setCountryData(scope);
		refreshCountryList(scope);
		scopeDialog.dialog('close');
	};
	var getUiTab = function(scope){
		var i=0, index;
		$(".tabs.ui-tabs-nav li", scope).each(function(e){
			if($(this).hasClass('ui-tabs-selected')){
				index = i;
			}
			i++;
		});
		return $('.ui-tabs-panel', scope).eq(index);
	};
	
	$('.cms-countrylist-item').bind('click', function(e){
		scope = $(this);
		scopeDialog = $( '#'+$(this).attr('dialog') );
		var t = $(e.target);
		if(!t.hasClass('ui-icon-close')){return true;}
			var mmm = t.parents('.b'), index;
			if(t.parent().text() == 'ALL'){
				var uitab = getUiTab( scopeDialog );
				$("p input", uitab).each(function(){
					this.checked = false;
				});
				t.parents('.a').remove();
			}else{
				var dps = $('em', t.parents('.d')), bps = $('em', t.parents('.b')), bcs = $('.c', t.parents('.b')), pins=t.parent().prev('ins'),nins=t.parent().next('ins');
				if(dps.length > 1){
					t.parent().remove();
					if(nins.length==0){pins.remove();}else{nins.remove();}
				}else if(dps.length == 1 && bcs.length > 1){
					t.parents('.c').remove();
				}else if(bcs.length == 1){
					t.parents('.a').remove();
				}else if(bps.length >1){
					t.parent().remove();
					if(nins.length==0){pins.remove();}else{nins.remove();}
				}else if(bps.length == 1){
					t.parents('.a').remove();
				}else{
					return true;
				}
				var matches = t.parent().text().match(/\([A-Z]+\)/g);
				var mname = matches[0].replace('(', '').replace(')', '');
				$("p input[name="+mname+"]", scopeDialog).each(function(){
					this.checked = false;
				});
			}
		setCountryDataByDel(scope);
	});
	$('.cms-countrylist .reset-btn').bind('click', function(e){
		scope = $(this).parents('.cms-countrylist-item');
		scopeDialog=$('#'+scope.attr('dialog'))
		$('.list', scope).html('');
		countryData.init(scope);
		countryData.set('');
		$("p input", scopeDialog).each(function(){
			this.checked = false;
		});
	});
	$('.cms-countrylist .select-btn').bind('click', function(e){
		scope = $(this).parents('.cms-countrylist-item');
		if(!scope.attr('dialog')){
			var genid1 = TVB.util.genId(),genid2 = TVB.util.genId();
			scopeDialog = $('.cms-countrylist-pop', scope).dialog({
				bgiframe: true,
				resizable: false,
				width: 800,
				position: 'top',
				autoOpen: false,
				modal: true,
				autoSize: true,
				title: 'Select Region/Country',
				buttons: {
					'Submit':function(e){
						submitTabsForm(e);
					}
				},
				'open': function (event,ui){
                    $("button.ui-button",$(this).parent()).removeClass("ui-button").addClass("cms-btn")
                }
			}).attr('id', genid2).attr('link', genid1);
			scope.attr('id', genid1).attr('dialog', genid2);
			initCountryTabs();
			initCountrySubTabs();
		}// init dialog end
		scopeDialog=$('#'+scope.attr('dialog'))
		scopeDialog.dialog('open');
		scopeDialog.tabs('option','selected', parseInt( $('.tabs', scopeDialog).attr('selectIndex'), 10 ) );
	});// click region/country btn end
	
};

TVB.Cms.Mod = {
    waitingDialog: function () {

        var $popWaiting = null;

        var init = function () {
            var tpl = '<div id="cms-pop-waiting" class="popup"><div class="bd loading"><p></p></div></div>';
            $popWaiting = $(tpl).appendTo('body').dialog({
                bgiframe: true,
                resizable: false,
                width: 520,
                autoOpen: false,
                modal: true
            });
        };

        return {
            freeze: false,
            freezeDuration: 500,
            open: function (title) {
                var that = this;
                if ($popWaiting === null) {
                    init();
                }
                if (typeof title !== 'undefined') {
                    $popWaiting.dialog('option', 'title', title);
                }
                $('#cms-pop-waiting div').addClass('loading').find('p').text('');
                $popWaiting.dialog('open');
                this.freeze = true;
                setTimeout(function () {that.freeze = false;}, that.freezeDuration);
            },
            close: function (callback) {
                var that = this;
                var timer = setInterval(function () {
                    if (that.freeze === false) {
                        clearInterval(timer);
                        $popWaiting.dialog('close');
                        if ($.isFunction(callback)) {
                            callback();
                        }
                    }
                }, 100);
            },
            showMsg: function (msg) {
                $('#cms-pop-waiting div').find('p').text(msg).end().removeClass('loading');
            }
        };

    },

    confirmDialog: function () {
        var $dialog = null;

        var init = function () {
            var tpl = '<div id="cms-pop-confirm" class="popup"><div class="bd"><p></p></div></div>';
            $dialog = $(tpl).appendTo('body').dialog({
                bgiframe: true,
                resizable: false,
                width: 520,
                autoOpen: false,
                modal: true
            });
        };

        //TODO

    }

};

TVB.Cms.uiInit = function (scope) { 

    var com = TVB.Cms.Components;
    var mod = TVB.Cms.Mod;

    TVB.util.once(com.header, scope);
    com.superfish(scope);
    com.laughing(scope);
    com.datepicker(scope);
    com.textarea(scope);
    com.time(scope);
    com.button(scope);
    com.label(scope);
    com.autocomplete(scope);
    com.jqgrid(scope);
	com.editableList(scope);
	com.dialog(scope);
	com.dragtosort(scope);
	com.countryList(scope);
	com.logout(scope);
	com.validation(scope);

};
